﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TCM.DbContextt;
using TCM.Models;
using System.Data.Entity;
using TCM.Common.Enums;

namespace TCM.Forms
{
    public partial class AddPlanToUser : Form
    {
        private readonly BaseContext _db;
        private List<User> _users;

        public AddPlanToUser()
        {
            InitializeComponent();
            
            _db = new BaseContext();

            _db.TestPlans.Load();
            _db.Users.Load();
            RefreshGrid();
            RefreshCombo();
        }

        private void RefreshGrid()
        {
            dataGridView1.DataSource = _db.TestPlans.Local.ToBindingList();
        }

        private void RefreshCombo()
        {
            _users = new List<User>();

            _users.AddRange(_db.Users.Local.ToList());

            comboBox1.DataSource = _users;
            comboBox1.DisplayMember = "Account";
            comboBox1.ValueMember = "UserId";

             
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            var data = _db.TestPlans.Where(x => x.Name.Contains(textBox1.Text));
            dataGridView1.DataSource = data.ToList();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            WorkWithTestPlan workWithTests = new WorkWithTestPlan();

            if (comboBox1.SelectedValue != null)
            {
                workWithTests.CurrentUserId = (Guid) comboBox1.SelectedValue;
            }
           
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                if (dataGridView1.Rows[i].Cells[1].Value != null)
                if ((bool) dataGridView1.Rows[i].Cells[1].Value)
                {
                    workWithTests.TestPlanId = (Guid)dataGridView1.Rows[i].Cells[0].Value;
                }
            }
            workWithTests.WorkWithTestPlanId = Guid.NewGuid();
            workWithTests.ChangeDate = DateTime.Today;
            workWithTests.State = (int)TestPlanStates.Open;
            _db.WorkWithTestPlans.Add(workWithTests);
            try
            {
                _db.SaveChanges();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            MessageBox.Show("Тест планы успешно привязаны");

        }


    }
}
